﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Windows.Forms;
using EquipmentConfig.Class;
using System.Threading;
using DevExpress.XtraEditors;
using System.Net.Sockets;
using System.Net;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing;
using Dexi.SoftwareHeartCheck.UI;
using System.Text.RegularExpressions;
using DevExpress.XtraPrinting;
using System.Collections.Concurrent;
using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.Office;
using System.Text;

namespace EquipmentConfig
{
    public partial class MainForm : Form
    {
        

        private SerialPort sp;
        /// <summary>
        /// 接收数据缓存
        /// </summary>
        public List<byte> recBuffer = new List<byte>();

        /// <summary>
        /// 串口是否连接
        /// </summary>
        private bool isSerialPort = false;

        /// <summary>
        /// 网口是否连接
        /// </summary>
        private bool isUdp = false;

        /// <summary>
        /// UDP连接
        /// </summary>
        public Socket client;

        /// <summary>
        /// 端口
        /// </summary>
        private int udpPort = 8868;

        /// <summary>
        /// UDP接收数据线程
        /// </summary>
        private Thread thReceiveData;

        /// <summary>
        /// 发送命令是否成功返回
        /// </summary>
        public static bool isSuccess = false;

        /// <summary>
        /// 发送命令是否成功返回
        /// </summary>
        public static bool isReadDeviceSuccess = false;

        /// <summary>
        /// 数据重发次数
        /// </summary>
        public int retryCount = 5;

        /// <summary>
        /// 实时数据类型，1：实时数据， 2：传感器调试，3：相机图片， 4：设备升级
        /// </summary>
        public int RealDataType = 0;

        /// <summary>
        /// 发送实时读取命令线程
        /// </summary>
        private Thread thSendRealDataCmd;

        /// <summary>
        /// 设备是否为升级状态
        /// </summary>
        public bool isUpgradeStatus = false;

        /// <summary>
        /// 设备升级数据包长度
        /// </summary>
        public int lengthPackages = 1024;

        /// <summary>
        /// 设备升级数据总包数
        /// </summary>
        public int totalPackages = 0;

        /// <summary>
        /// 设备升级数据当前包数
        /// </summary>
        public int indexPackages = 0;

        /// <summary>
        /// 设备升级发送每包数据返回状态， -1：未发送，0：成功，1：校验错误，2：文件大小不对，3：其他错误
        /// </summary>
        public int upgradeStatus = -1;

        /// <summary>
        /// 采集图片数据返回状态， -1：未发送，0x00：图片缓存存在，0xFF 图片缓存不存在
        /// </summary>
        public int imageStatus = -1;

        /// <summary>
        /// 实时数据读取状态
        /// </summary>
        public bool RealDataReadStatus = false;

        /// <summary>
        /// 实时数据是否上报数据
        /// </summary>
        public bool isRealDataUpload = false;

        /// <summary>
        /// 实时数据是否采集图片
        /// </summary>
        public bool isCollectImage = false;

        /// <summary>
        /// 实时数据是否上报图片
        /// </summary>
        public bool isUploadImage = false;

        /// <summary>
        /// 升级文件字节集合
        /// </summary>
        public List<byte> listUpgradeFile = new List<byte>();

        /// <summary>
        /// 设备配置
        /// </summary>
        public RTUParameterConfig.ParameterConfig paraConfig = new RTUParameterConfig.ParameterConfig();

        /// <summary>
        /// 原始设备配置信息
        /// </summary>
        public static RTUParameterConfig.Class.StructData.RtuConfigInfo rtuConfigInfo_Before;

        /// <summary>
        ///已配置的设备配置信息
        /// </summary>
        public static RTUParameterConfig.Class.StructData.RtuConfigInfo rtuConfigInfo;

        /// <summary>
        /// 流量堰槽数据
        /// </summary>
        public double[] flowData = new double[256];

        /// <summary>
        /// 设备信息数据表
        /// </summary>
        public DataTable dtDeviceInfo = new DataTable();

        /// <summary>
        /// 传感器调试窗口
        /// </summary>
        public DebugInfo debugInfo;

        /// <summary>
        /// 数据调试窗口
        /// </summary>
        public AllDebugInfo dataDebugInfo;

        /// <summary>
        /// 相机图片调试窗口
        /// </summary>
        public CameraPicture cameraPicture;

        /// <summary>
        /// 流量堰槽设置窗口
        /// </summary>
        public FlowWeirGroove flowWeirGroove;

        /// <summary>
        /// 水位流量标定窗口
        /// </summary>
        public WaterLevelSetting waterLevelSetting;

        /// <summary>
        /// 登录ID
        /// </summary>
        public static int loginID = 0;

        /// <summary>
        /// 消息ID
        /// </summary>
        public const int debugMsg = 1025;

        /// <summary>
        /// 数据调试信息
        /// </summary>
        public static string debugMessage = string.Empty;

        /// <summary>
        /// 是否加载完成
        /// </summary>
        public bool IsLoaded = false;

        /// <summary>
        /// 设备标识
        /// </summary>
        public int deviceIndex = 0;

        /// <summary>
        /// 图片分包数据
        /// </summary>
        public Dictionary<int, byte[]> imageDataPackages = new Dictionary<int, byte[]>();

        /// <summary>
        /// 图片开始上传时间
        /// </summary>
        public DateTime imageStartTime;

        /// <summary>
        /// 累计流量值
        /// </summary>
        public decimal totalFlowValue = 0;

        /// <summary>
        /// 雨量值
        /// </summary>
        public decimal totalRainValue = 0;

        /// <summary>
        /// 历史数据起始时间
        /// </summary>
        public DateTime? hisDataStartTime = null;

        /// <summary>
        /// 历史数据表
        /// </summary>
        public DataTable dtHisData = new DataTable();

        public bool isOneLoad = true;

        public bool isRemoveHistory = false;
        public string removeDate = "";

        /// <summary>
        /// 设备配置数据长度
        /// </summary>
        public int intConfigDataLength = 968;

        public MainForm()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }
       
        private void MainForm_Load(object sender, EventArgs e)
        {
            dtHisData.Columns.Add("采集时间");
            dtHisData.Columns.Add("水位1(m)");
            dtHisData.Columns.Add("水位2(m)");
            dtHisData.Columns.Add("流速1(m/s)");
            dtHisData.Columns.Add("流速2(m/s)");
            dtHisData.Columns.Add("流量计1水位(m)");
            dtHisData.Columns.Add("流量计2水位(m)");
            dtHisData.Columns.Add("流量计1流速(m/s)");
            dtHisData.Columns.Add("流量计2流速(m/s)");
            dtHisData.Columns.Add("闸位计1(m)");
            dtHisData.Columns.Add("闸位计2(m)");
            dtHisData.Columns.Add("瞬时流量1(m3/s)");
            dtHisData.Columns.Add("瞬时流量2(m3/s)");
            dtHisData.Columns.Add("累计流量1(m3)");
            dtHisData.Columns.Add("累计流量2(m3)");
            dtHisData.Columns.Add("累计雨量(mm)");
            dtHisData.Columns.Add("日降雨量(mm)");
            dtHisData.Columns.Add("1分钟降雨量(mm)");
            dtHisData.Columns.Add("5分钟降雨量(mm)");
            dtHisData.Columns.Add("10分钟降雨量(mm)");
            dtHisData.Columns.Add("30分钟降雨量(mm)");
            dtHisData.Columns.Add("60分钟降雨量(mm)");
            dtHisData.Columns.Add("浊度(NTU)");
            dtHisData.Columns.Add("PH");
            dtHisData.Columns.Add("溶解氧(mg/L)");
            dtHisData.Columns.Add("电导率(uS/cm)");
            dtHisData.Columns.Add("COD(uS/cm)");
            dtHisData.Columns.Add("氨氮(mg/L)");
            dtHisData.Columns.Add("余氯(mg/L)");
            dtHisData.Columns.Add("水温(℃)");
            dtHisData.Columns.Add("设备温度(℃)");
            dtHisData.Columns.Add("设备电压(V)");//01 9A FF FF
            dtHisData.Columns.Add("土壤1温度(℃)");
            dtHisData.Columns.Add("土壤2温度(℃)");
            dtHisData.Columns.Add("土壤3温度(℃)");
            dtHisData.Columns.Add("土壤4温度(℃)");
            dtHisData.Columns.Add("土壤5温度(℃)");
            dtHisData.Columns.Add("土壤6温度(℃)");
            dtHisData.Columns.Add("土壤7温度(℃)");
            dtHisData.Columns.Add("土壤8温度(℃)");
            dtHisData.Columns.Add("土壤1湿度(%)");
            dtHisData.Columns.Add("土壤2湿度(%)");
            dtHisData.Columns.Add("土壤3湿度(%)");
            dtHisData.Columns.Add("土壤4湿度(%)");
            dtHisData.Columns.Add("土壤5湿度(%)");
            dtHisData.Columns.Add("土壤6湿度(%)");
            dtHisData.Columns.Add("土壤7湿度(%)");
            dtHisData.Columns.Add("土壤8湿度(%)");
            dtHisData.Columns.Add("渗压力1(MPa)");
            dtHisData.Columns.Add("渗压力2(MPa)");
            dtHisData.Columns.Add("渗压力3(MPa)");
            dtHisData.Columns.Add("渗压力4(MPa)");
            dtHisData.Columns.Add("渗压力5(MPa)");
            dtHisData.Columns.Add("渗压力6(MPa)");
            dtHisData.Columns.Add("渗压力7(MPa)");
            dtHisData.Columns.Add("渗压力8(MPa)");

            cbbNud1.Properties.Items.Add(new ListItem("1", 1));
            cbbNud1.Properties.Items.Add(new ListItem("2", 2));
            cbbNud1.Properties.Items.Add(new ListItem("3", 3));
            cbbNud1.Properties.Items.Add(new ListItem("4", 4));
            cbbNud1.Properties.Items.Add(new ListItem("5", 5));
            cbbNud1.Properties.Items.Add(new ListItem("6", 6));
            cbbNud1.Properties.Items.Add(new ListItem("10", 10));
            cbbNud1.Properties.Items.Add(new ListItem("12", 12));
            cbbNud1.Properties.Items.Add(new ListItem("15", 15));
            cbbNud1.Properties.Items.Add(new ListItem("20", 20));
            cbbNud1.Properties.Items.Add(new ListItem("30", 30));
            cbbNud1.Properties.Items.Add(new ListItem("60", 60));
            cbbNud1.Properties.Items.Add(new ListItem("120", 120));
            cbbNud1.Properties.Items.Add(new ListItem("180", 180));
            cbbNud1.Properties.Items.Add(new ListItem("240", 240));
            cbbNud1.SelectedIndex = 0;
            
            Common.ClearFile(System.Windows.Forms.Application.StartupPath + "\\image\\");
            dgvInfo.AutoGenerateColumns = false;
            paraConfig.showPassWord = Program.showPassWord;
            paraConfig.InitShowControl(loginID);
            paraConfig.SetValue(this.Text);
            paraConfig.Dock = DockStyle.Fill;
            plnSetting.Controls.Add(paraConfig);

            if (Program.showPassWord == "0")
            {
                btnClearHisData.Visible = true;
            }

            thSendRealDataCmd = new Thread(RealDataSendCmd);
            thSendRealDataCmd.IsBackground = true;
            thSendRealDataCmd.Start();
            dgvInfo.DataSource = dtDeviceInfo;
            xtcMenu.SelectedTabPageIndex = 0;
            timer2.Enabled = true;
            IsLoaded = true;
            Thread.Sleep(500);
            SendCmd(Protocol.GetReadDeviceInfoCmd(0x02)); //读取设备配置
        }

        public void InitFormStatus(bool blnShow)
        {
            xtraTabPage5.PageVisible = blnShow;
            xtraTabPage8.PageVisible = blnShow;
            xtraTabPage6.PageVisible = blnShow;
            xtraTabPage9.PageVisible = blnShow;
        }

        public void BindHisData()
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                dgvHisData.DataSource = dtHisData.Copy();
            });
        }

        /// <summary>
        /// 发送设备命令
        /// </summary>
        public void SendDeviceCmd()
        {
            SendCmd(Protocol.GetReadDeviceInfoCmd(0x01));
        }

        ///// <summary>
        ///// 设置连接状态
        ///// </summary>
        ///// <param name="blnStatus">true,false</param>
        //public void SetClientStatus(bool blnStatus)
        //{
        //    nbClient.Visible = blnStatus;
        //    nbClose.Visible = !blnStatus;
        //    //xtcMenu.Visible = !nbClient.Visible;
        //}

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="strPortName">串口</param>
        /// <returns>true,false</returns>
        public bool OpenSerialPort(string strPortName)
        {
            try
            {
                sp = new SerialPort();
                sp.DataReceived += Sp_DataReceived;
                //sp.ReadTimeout = -1;
                sp.ReceivedBytesThreshold = 1;
                sp.PortName = strPortName;
                sp.BaudRate = 115200;
                sp.DataBits = 8;
                sp.StopBits = StopBits.One;
                sp.Parity = Parity.None;//不发生奇偶校验检查
                sp.Open();
                isSerialPort = true;
                return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("打开串口失败！", ex);
                return false;
            }
        }

        /// <summary>
        /// 网口连接
        /// </summary>
        /// <param name="strIP">IP</param>
        /// <returns>true,false</returns>
        public bool InitUdpClient(string strIP)
        {
            try
            {
                if (!Common.CheckClient(strIP))
                {
                    Messages.ShowAlertDialog("设备IP地址无法连接,请检查网络连接！",false);
                    return false;
                }

                thReceiveData = new Thread(ReceiveData);
                thReceiveData.IsBackground = true;
                thReceiveData.Start();

                client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.Connect(new IPEndPoint(IPAddress.Parse(strIP), udpPort));
                isUdp = true;
                return true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("建立连接失败！" ,ex);
                return false;
            }
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="index"></param>
        public void CloseConnection(int index)
        {
            if (index == 0)
            {
                sp.Close();
                sp = null;
                isSerialPort = false;
            }

            if (index == 1)
            {
                client.Close();
                client.Dispose();
                isUdp = false;
                thReceiveData.Abort();
            }
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="bytes">发送数据</param>
        public bool SendCmd(byte[] bytes)
        {
            try
            {
                if (isSerialPort)
                {
                    if (sp.IsOpen)
                    {
                        //Thread.Sleep(200);
                        sp.Write(bytes, 0, bytes.Length);
                        if (IsLoaded)
                        {
                            statusStrip.Invoke((MethodInvoker)delegate
                            {
                                labInfo1.Text = string.Format("连接串口{0}成功  发送数据:{1}字节", sp.PortName, bytes.Length);
                            });
                        }
                        return true;
                    }
                }

                //if (isUdp)
                //{
                //    if (client != null && client.Connected)
                //    {
                //        client.Send(bytes);
                //        return true;
                //    }
                //}
                return false;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("发送数据失败！" , ex);
                return false;
            }
        }

        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <param name="byteData">设备信息字节数组</param>
        /// <returns>true,false</returns>
        private bool GetDeviceInfo(byte[] byteData)
        {
            object objInfo = Protocol.BytesToStuct(byteData, typeof(StructData.Device_Info));
            if (objInfo != null)
            {
                StructData.Device_Info di = (StructData.Device_Info)objInfo;
                DataTable dt = new DataTable();
                dt.Columns.Add("Name");
                dt.Columns.Add("Value");
                DataRow dr = dt.NewRow();
                dr[0] = "序列号";
                dr[1] = new string(di.SN);
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "硬件版本";
                dr[1] = "V" + (BitConverter.ToUInt16(di.HardwaveVer.Reverse().ToArray(), 0) / 100.0).ToString("F");
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "软件版本";
                byte[] bv = new byte[2];
                bv[0] = di.ProgramVer[1];
                bv[1] = di.ProgramVer[0];
                byte[] by = new byte[2];
                by[0] = di.ProgramVer[3];
                by[1] = di.ProgramVer[2];
                dr[1] = "V" + (BitConverter.ToUInt16(bv, 0) / 100.0).ToString("F") + "_" + BitConverter.ToUInt16(by, 0) + "-" + di.ProgramVer[4] + "-" + di.ProgramVer[5] + "_(" + di.ProgramVer[6] + ")(" + di.ProgramVer[7] + ")";
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "BIOS版本";
                dr[1] = "V" + (BitConverter.ToUInt16(di.BiosVer.Reverse().ToArray(), 0) / 100.0).ToString("F");
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "电源电压";
                dr[1] = BitConverter.ToUInt16(di.Voltage.Reverse().ToArray(), 0) / 100.0 + "V";
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "设备温度";
                double t = BitConverter.ToUInt16(di.Temperature.Reverse().ToArray(), 0) / 10.0;
                dr[1] = di.Temperature[0] == 1 ? "-" + t.ToString() + "℃" :  t.ToString() + "℃";
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "数据采集周期";
                dr[1] = Convert.ToString(di.DataAcquisitionCycle) + "分钟";
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "SIM卡状态";
                dr[1] = "";
                if (di.SIMStatus == 0)
                {
                    dr[1] = "未使用GPRS";
                }
                if (di.SIMStatus == 1)
                {
                    dr[1] = "SIM卡就绪";
                }
                if (di.SIMStatus == 2)
                {
                    dr[1] = "SIM卡错误";
                }
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "GPRS网络制式";
                dr[1] = "";
                if (di.GSMType == 1)
                {
                    dr[1] = "移动运营商";
                }
                if (di.GSMType == 2)
                {
                    dr[1] = "电信运营商";
                }
                if (di.GSMType == 3)
                {
                    dr[1] = "联通运营";
                }
                if (di.GSMType == 0x0F)
                {
                    dr[1] = "未识别网络";
                }
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "GPRS信号强度";
                dr[1] = di.Signal;
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "设备时间";
                dr[1] = DateTime.Now.Year.ToString().Substring(0, 2) + di.DeviceTime[0].ToString().PadLeft(2, '0') + "/" + di.DeviceTime[1].ToString().PadLeft(2, '0') + "/" + di.DeviceTime[2].ToString().PadLeft(2, '0')
                    + " " + di.DeviceTime[3].ToString().PadLeft(2, '0') + ":" + di.DeviceTime[4].ToString().PadLeft(2, '0') + ":" + di.DeviceTime[5].ToString().PadLeft(2, '0');
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "中心站1接口";
                dr[1] = "";
                if (di.CenterStatus1 == 0)
                {
                    dr[1] = "关闭";
                }
                if (di.CenterStatus1 == 1)
                {
                    dr[1] = "GPRS/3G/4G";
                }
                if (di.CenterStatus1 == 2)
                {
                    dr[1] = "有线以太网";
                }
                else if (di.CenterStatus1 == 3)
                {
                    dr[1] = "RS485通道3透传";
                }
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "中心站2接口";
                dr[1] = "";
                if (di.CenterStatus2 == 0)
                {
                    dr[1] = "关闭";
                }
                if (di.CenterStatus2 == 1)
                {
                    dr[1] = "GPRS/3G/4G";
                }
                if (di.CenterStatus2 == 2)
                {
                    dr[1] = "有线以太网";
                }
                else if (di.CenterStatus2 == 3)
                {
                    dr[1] = "RS485通道3透传";
                }
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "中心站3接口";
                dr[1] = "";
                if (di.CenterStatus3 == 0)
                {
                    dr[1] = "关闭";
                }
                if (di.CenterStatus3 == 1)
                {
                    dr[1] = "GPRS/3G/4G";
                }
                if (di.CenterStatus3 == 2)
                {
                    dr[1] = "有线以太网";
                }
                else if (di.CenterStatus3 == 3)
                {
                    dr[1] = "RS485通道3透传";
                }
                dt.Rows.Add(dr);

                string strIP1 = string.Empty;
                string strIP2 = string.Empty;
                string strIP3 = string.Empty;
                if (rtuConfigInfo.CentralStationIP1 != null)
                {
                    strIP1 = rtuConfigInfo.CentralStationIP1[0].ToString() + "." + rtuConfigInfo.CentralStationIP1[1].ToString() + "." + rtuConfigInfo.CentralStationIP1[2].ToString() + "." + rtuConfigInfo.CentralStationIP1[3].ToString() + ":" + Common.BytesToShort(rtuConfigInfo.CentralStationPort1[0], rtuConfigInfo.CentralStationPort1[1]).ToString();
                    strIP2 = rtuConfigInfo.CentralStationIP2[0].ToString() + "." + rtuConfigInfo.CentralStationIP2[1].ToString() + "." + rtuConfigInfo.CentralStationIP2[2].ToString() + "." + rtuConfigInfo.CentralStationIP2[3].ToString() + ":" + Common.BytesToShort(rtuConfigInfo.CentralStationPort2[0], rtuConfigInfo.CentralStationPort2[1]).ToString();
                    strIP3 = rtuConfigInfo.CentralStationIP3[0].ToString() + "." + rtuConfigInfo.CentralStationIP3[1].ToString() + "." + rtuConfigInfo.CentralStationIP3[2].ToString() + "." + rtuConfigInfo.CentralStationIP3[3].ToString() + ":" + Common.BytesToShort(rtuConfigInfo.CentralStationPort3[0], rtuConfigInfo.CentralStationPort3[1]).ToString();
                }
                dr = dt.NewRow();
                dr[0] = "中心站1上传状态";
                dr[1] = "";
                if (di.CenterUploadStatus1 == 0)
                {
                    dr[1] = "中心站{0}准备就绪";
                }
                if (di.CenterUploadStatus1 == 1)
                {
                    dr[1] = "中心站{0}发送中……";
                }
                if (di.CenterUploadStatus1 == 2)
                {
                    dr[1] = "中心站{0}发送成功";
                }
                if (di.CenterUploadStatus1 == 0xF1)
                {
                    dr[1] = "中心站{0}发送失败";
                }
                if (di.CenterUploadStatus1 == 0xFF)
                {
                    dr[1] = "中心站没有开启";
                }
                else
                {
                    dr[1] = string.Format(dr[1].ToString(), strIP1) + ",成功次数: " + BitConverter.ToUInt16(di.CenterSendSuccessCount1.Reverse().ToArray(), 0) + ",失败次数: " + BitConverter.ToUInt16(di.CenterFailCount1.Reverse().ToArray(), 0) + ",总发送次数: " + BitConverter.ToUInt16(di.CenterCacheCount1.Reverse().ToArray(), 0);
                }
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "中心站2上传状态";
                dr[1] = "";
                if (di.CenterUploadStatus2 == 0)
                {
                    dr[1] = "中心站{0}准备就绪";
                }
                if (di.CenterUploadStatus2 == 1)
                {
                    dr[1] = "中心站{0}发送中……";
                }
                if (di.CenterUploadStatus2 == 2)
                {
                    dr[1] = "中心站{0}发送成功";
                }

                if (di.CenterUploadStatus2 == 0xF1)
                {
                    dr[1] = "中心站{0}发送失败";
                }
                if (di.CenterUploadStatus2 == 0xFF)
                {
                    dr[1] = "中心站没有开启";
                }
                else
                {
                    dr[1] = string.Format(dr[1].ToString(), strIP2) + ",成功次数: " + BitConverter.ToUInt16(di.CenterSendSuccessCount2.Reverse().ToArray(), 0) + ",失败次数: " + BitConverter.ToUInt16(di.CenterFailCount2.Reverse().ToArray(), 0) + ",总发送次数: " + BitConverter.ToUInt16(di.CenterCacheCount2.Reverse().ToArray(), 0);
                }
                dt.Rows.Add(dr);

                dr = dt.NewRow();
                dr[0] = "中心站3上传状态";
                dr[1] = "";
                if (di.CenterUploadStatus3 == 0)
                {
                    dr[1] = "中心站{0}准备就绪";
                }
                if (di.CenterUploadStatus3 == 1)
                {
                    dr[1] = "中心站{0}发送中……";
                }
                if (di.CenterUploadStatus3 == 2)
                {
                    dr[1] = "中心站{0}发送成功";
                }

                if (di.CenterUploadStatus3 == 0xF1)
                {
                    dr[1] = "中心站{0}发送失败";
                }
                if (di.CenterUploadStatus3 == 0xFF)
                {
                    dr[1] = "中心站没有开启";
                }
                else
                {
                    dr[1] = string.Format(dr[1].ToString(), strIP3) + ",成功次数: " + BitConverter.ToUInt16(di.CenterSendSuccessCount3.Reverse().ToArray(), 0) + ",失败次数: " + BitConverter.ToUInt16(di.CenterFailCount3.Reverse().ToArray(), 0) + ",总发送次数: " + BitConverter.ToUInt16(di.CenterCacheCount3.Reverse().ToArray(), 0);
                }
                dt.Rows.Add(dr);
             
                int b1 = Common.GetIntBit(di.SystemStatus[3], 0);
                int b2 = Common.GetIntBit(di.SystemStatus[3], 1);
                int b3 = Common.GetIntBit(di.SystemStatus[3], 2);
                int b4 = Common.GetIntBit(di.SystemStatus[3], 3);
                int b5 = Common.GetIntBit(di.SystemStatus[3], 4);
                int b6 = Common.GetIntBit(di.SystemStatus[3], 5);
                int b7 = Common.GetIntBit(di.SystemStatus[3], 6);
                int b8 = Common.GetIntBit(di.SystemStatus[3], 7);
                int b9 = Common.GetIntBit(di.SystemStatus[2], 0);
                int b10 = Common.GetIntBit(di.SystemStatus[2], 1);

                if (b9 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "主时钟";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b10 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "字库";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b1 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "RTC时钟";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b2 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "供电电压";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b3 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "温度";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b4 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "SRAM";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b5 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "4G";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b6 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "有线网络";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b7 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "FLASH";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                if (b8 == 1)
                {
                    dr = dt.NewRow();
                    dr[0] = "TF卡";
                    dr[1] = "异常故障";
                    dt.Rows.Add(dr);
                }

                //测试
                //dr = dt.NewRow();
                //dr[0] = "RTC时钟";
                //dr[1] = b2 == 1 ? "异常故障" : "正常";
                //dt.Rows.Add(dr);

                //dr = dt.NewRow();
                //dr[0] = "SRAM";
                //dr[1] = b5 == 1 ? "异常故障" : "正常";
                //dt.Rows.Add(dr);

                //dr = dt.NewRow();
                //dr[0] = "4G";
                //dr[1] = b6 == 1 ? "异常故障" : "正常";
                //dt.Rows.Add(dr);

                //dr = dt.NewRow();
                //dr[0] = "有线网络";
                //dr[1] = b7 == 1 ? "异常故障" : "正常";
                //dt.Rows.Add(dr);

                //dr = dt.NewRow();
                //dr[0] = "FLASH";
                //dr[1] = b8 == 1 ? "异常故障" : "正常";
                //dt.Rows.Add(dr);

                //dr = dt.NewRow();
                //dr[0] = "TF卡";
                //dr[1] = b9 == 1 ? "异常故障" : "正常";
                //dt.Rows.Add(dr);

                dtDeviceInfo = dt.Copy();
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取流量堰槽数据
        /// </summary>
        /// <param name="byteData">流量堰槽数据字节数组</param>
        /// <returns>true,false</returns>
        private double[] GetFlowData(byte[] byteData)
        {
            double[] dblData = new double[256];
            if (byteData.Length != 1024)
            {
                return dblData;
            }

            for (int i = 0; i < flowData.Length; i++)
            {
                dblData[i] = BitConverter.ToInt32(byteData, i * 4) / 100000.0;
            }
            return dblData;
        }

        /// <summary>
        /// 获取设备配置信息
        /// </summary>
        /// <param name="byteRec">设备配置信息</param>
        /// <returns>true,false</returns>
        private bool GetDeviceConfig(byte[] byteRec)
        {
            intConfigDataLength = byteRec.Length;
            List<byte> listData = new List<byte>();
            if (byteRec.Length == 968)
            {
                listData.AddRange(byteRec);
                listData.AddRange(new byte[1400 - 968]);
                byteRec = listData.ToArray();
            }
            
            object objRtu1 = Protocol.BytesToStuct(byteRec, typeof(RTUParameterConfig.Class.StructData.RtuConfigInfo));
            //object objRtu2 = Protocol.BytesToStuct(byteRec, typeof(RTUParameterConfig.Class.StructData.RtuConfigInfo));
            if (objRtu1 != null)
            {
                rtuConfigInfo = (RTUParameterConfig.Class.StructData.RtuConfigInfo)objRtu1;
                //rtuConfigInfo_Before = (RTUParameterConfig.Class.StructData.RtuConfigInfo)objRtu2;
                if (isOneLoad)
                {
                    rtuConfigInfo_Before = rtuConfigInfo;
                    isOneLoad = false;
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        private int GetItemIndex(ComboBoxEdit cbb, int intValue)
        {
            for (int i = 0; i < cbb.Properties.Items.Count; i++)
            {
                if ((cbb.Properties.Items[i] as ListItem).Value == intValue)
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 处理网口数据
        /// </summary>
        private void ReceiveData()
        {
            while (true)
            {
                try
                {
                    if (client != null)
                    {
                        byte[] buff = new byte[1024 * 10];
                        int length = client.Receive(buff);
                        byte[] byteRec = new byte[length];
                        Array.Copy(buff, 0, byteRec, 0, byteRec.Length);
                        recBuffer.AddRange(byteRec);
                        InitRtuData();
                    }
                }
                catch(Exception ex)
                {
                    Messages.SaveLog(ex);
                    continue;
                }
            }
        }

        private void SetUpgradeStatus()
        {
            RealDataType = 0;
            //totalPackages = 0;
            //indexPackages = 0;
            upgradeStatus = -1;
            isUpgradeStatus = false;
            this.BeginInvoke((MethodInvoker)delegate
            {
                btnUpload.Text = "开始升级";
                SetUpdateFormStatus(true);
            });
        }

        public void InitHisData(byte[] recData)
        {
            if (recData.Length >= 1000)
            {
                List<byte> listData = recData.ToList<byte>();
                DataRow dr = dtHisData.NewRow();

                dr[0] = (Convert.ToUInt16(listData[1]) + 2000).ToString() + "-" + Convert.ToUInt16(listData[2]).ToString().ToString().PadLeft(2, '0') + "-" + Convert.ToUInt16(listData[3]).ToString().ToString().PadLeft(2, '0')
                                                            + " " + Convert.ToUInt16(listData[4]).ToString().ToString().PadLeft(2, '0') + ":" + Convert.ToUInt16(listData[5]).ToString().ToString().PadLeft(2, '0') + ":00";
                List<byte> listValue = listData.GetRange(6, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[1] = BitConverter.ToInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(10, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[2] = BitConverter.ToInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(14, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[3] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(18, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[4] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(22, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[5] = BitConverter.ToInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(26, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[6] = BitConverter.ToInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(30, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[7] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                    
                }

                listValue = listData.GetRange(34, 4);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF && listValue[2] == 0xFF && listValue[3] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[8] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(38, 4);
                if (listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[9] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(42, 4);
                if (listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[10] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(46, 8);
                if (listValue.Where(x => x == 0xFF).Count() != 8)
                {
                    dr[11] = BitConverter.ToUInt64(listValue.Reverse<byte>().ToArray(), 0) / 3600.0 / 100000.0;
                }

                listValue = listData.GetRange(54, 8);
                if (listValue.Where(x => x == 0xFF).Count() != 8)
                {
                    dr[12] = BitConverter.ToUInt64(listValue.Reverse<byte>().ToArray(), 0) / 3600.0 / 100000.0;
                }

                listValue = listData.GetRange(62, 8);
                if (listValue.Where(x => x == 0xFF).Count() != 8)
                {
                    dr[13] = BitConverter.ToUInt64(listValue.Reverse<byte>().ToArray(), 0) / 100000.0;
                }

                listValue = listData.GetRange(70, 8);
                if (listValue.Where(x => x == 0xFF).Count() != 8)
                {
                    dr[14] = BitConverter.ToUInt64(listValue.Reverse<byte>().ToArray(), 0) / 100000.0;
                }

                listValue = listData.GetRange(78, 4);
                if (listValue.Where(x => x == 0xFF).Count() != 4)
                {
                    dr[15] = BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(82, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[16] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(84, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[17] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(86, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[18] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(88, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[19] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(90, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[20] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(92, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[21] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(94, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[22] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(96, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[23] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(98, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[24] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(100, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[25] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(102, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[26] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(104, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[27] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(106, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[28] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(108, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[29] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(110, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[30] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 100.0;
                }

                listValue = listData.GetRange(112, 2);
                if (listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[31] = BitConverter.ToUInt16(listValue.Reverse<byte>().ToArray(), 0) / 1000.0;
                }

                listValue = listData.GetRange(114, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[32] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(116, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[33] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(118, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[34] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(120, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[35] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(122, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[36] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(124, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[37] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(126, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[38] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(128, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[39] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(130, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[40] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(132, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[41] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(134, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[42] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(136, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[43] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(138, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[44] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(140, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[45] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(142, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[46] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(144, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[47] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(146, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[48] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(148, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[49] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(150, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[50] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(152, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[51] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(154, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[52] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(156, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[53] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(158, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[54] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                listValue = listData.GetRange(160, 2);
                if (!(listValue[0] == 0x7F && listValue[1] == 0xFF) && listValue.Where(x => x == 0xFF).Count() != 2)
                {
                    dr[55] = BitConverter.ToInt16(listValue.Reverse<byte>().ToArray(), 0) / 10.0;
                }

                dtHisData.Rows.Add(dr);
            }       
        }

        /// <summary>
        /// 发送实时数据
        /// </summary>
        private void RealDataSendCmd()
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(100);    
                    if(RealDataType == 1)//实时数据
                    {
                        //if (RealDataReadStatus)//读取实时数据
                        //{
                        //    SendCmd(Protocol.GetReadDeviceInfoCmd(0X09));
                        //    Thread.Sleep(1000);
                        //}

                        //if (isRealDataUpload)//上报数据
                        //{
                        //    if (SendCmd(Protocol.GetReadDeviceInfoCmd(0X09)))
                        //    {
                        //        isRealDataUpload = false;
                        //    }
                        //    Thread.Sleep(1000);
                        //}

                        //if (isUploadImage)//上报图片
                        //{
                        //    if (SendCmd(Protocol.GetReadDeviceInfoCmd(0X09)))
                        //    {
                        //        isUploadImage = false;
                        //    }
                        //    Thread.Sleep(1000);
                        //}
                    }

                    if (RealDataType == 3)//相机图片 开始采集
                    {
                        TimeSpan ts = DateTime.Now - imageStartTime;
                        if (ts.TotalSeconds > 60)
                        {
                            if (cameraPicture != null)
                            {
                                cameraPicture.ShowInfo(7);//采集超时
                            }
                            Thread.Sleep(1000);
                        }
                    }

                    if (RealDataType == 5)//相机图片 上报图片
                    {
                        TimeSpan ts = DateTime.Now - imageStartTime;
                        if (ts.TotalMinutes > 5)
                        {
                            if (cameraPicture != null)
                            {
                                cameraPicture.ShowInfo(8);//超时
                            }
                            Thread.Sleep(1000);
                        }

                        //if (!isCollectImage)//采集中
                        //{
                        //    //isSuccess = false;
                        //    Thread.Sleep(1000);
                        //    SendCmd(Protocol.GetWriteDeviceCmd(0x0C, new byte[2] { Convert.ToByte(deviceIndex), 0x02 }));
                        //}
                    }

                    if (RealDataType == 4)//设备升级
                    {
                        indexPackages += 1;
                        for (int i = 0; i < retryCount + 1; i++)
                        {
                            //if (i == 5)
                            //{
                            //    SetUpgradeStatus();
                            //    Messages.ShowAlertDialog("设备升级超时，请检查设备连接！", false);
                            //    break;
                            //}

                            byte[] data = listUpgradeFile.GetRange(0, lengthPackages).ToArray();
                            SendCmd(Protocol.GetWriteDeviceUpgradeCmd(data, indexPackages, totalPackages));
                            //if (indexPackages == 1)//第一包数据等待3秒
                            //{
                            //    Thread.Sleep(3000);
                            //}
                            //else
                            //{
                            //    Thread.Sleep(50);
                            //for (int m = 0; m < 20; m++)
                            //{
                            //    Thread.Sleep(50);
                            //    if (upgradeStatus != -1)
                            //    {
                            //        break;
                            //    }
                            //}
                            //}

                            if (upgradeStatus == 0)//成功
                            {
                                upgradeStatus = -1;
                                listUpgradeFile.RemoveRange(0, lengthPackages);
                                this.BeginInvoke((MethodInvoker)delegate
                                {
                                    if (totalPackages != 0 && indexPackages % 5 == 0)
                                    {
                                        progressBar.Value = Convert.ToInt16(Math.Round((double)indexPackages / totalPackages, 2, MidpointRounding.AwayFromZero) * 100);
                                        labProgress.Text = progressBar.Value.ToString() + "%";
                                    }
                                });

                                if (indexPackages != 0 && totalPackages != 0 && indexPackages == totalPackages)
                                {
                                    SetUpgradeStatus();
                                    Messages.ShowAlertDialog("设备升级成功！", true);
                                }
                                break;
                            }

                            if (upgradeStatus == 1 || upgradeStatus == 2 || upgradeStatus == 3)
                            {
                                SetUpgradeStatus();
                                Messages.ShowAlertDialog("设备升级数据错误", false);
                                break;
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                    Messages.SaveLog(ex);
                    continue;
                }
            }
        }

        /// <summary>
        /// 设备实时数据读取界面状态
        /// </summary>
        public void SetRealDataFormStatus(bool blnStatus)
        {
            xtraTabPage1.PageEnabled = blnStatus;
            xtraTabPage5.PageEnabled = blnStatus;
            xtraTabPage8.PageEnabled = blnStatus;
            xtraTabPage9.PageEnabled = blnStatus;

            btnCollect.Enabled = !blnStatus;
            btnUpLoadData.Enabled = !blnStatus;
            btnImageCollect.Enabled = !blnStatus;
            btnUploadImage.Enabled = !blnStatus;
        }

        /// <summary>
        /// 设置设备升级界面状态
        /// </summary>
        public void SetUpdateFormStatus(bool blnStatus)
        {
            xtraTabPage1.PageEnabled = blnStatus;
            xtraTabPage5.PageEnabled = blnStatus;
            xtraTabPage6.PageEnabled = blnStatus;
            xtraTabPage8.PageEnabled = blnStatus;
            timer2.Enabled = blnStatus;
        }

        /// <summary>
        /// 设置传感器调试界面状态
        /// </summary>
        public void SetDebugStatus(bool blnStatus)
        {
            xtraTabPage1.PageEnabled = blnStatus;
            xtraTabPage5.PageEnabled = blnStatus;
            xtraTabPage8.PageEnabled = blnStatus;
            xtraTabPage9.PageEnabled = blnStatus;
            xtraTabPage13.PageEnabled = blnStatus;
            timer2.Enabled = blnStatus;
        }

        public void SetImageCmd(int intPackages)
        {
            List<byte> listData = new List<byte>();
            listData.Add(Convert.ToByte(deviceIndex));
            listData.Add(0);
            listData.AddRange(BitConverter.GetBytes((ushort)intPackages).Reverse<byte>());
            SendCmd(Protocol.GetWriteDeviceCmd(0x0D, listData.ToArray()));
        }

        /// <summary>
        /// 加载RTU数据
        /// </summary>
        public void InitRtuData()
        {
            try
            {
                if (recBuffer.Count > 0)
                {
                    if (recBuffer.Count < 8)
                    {
                        recBuffer.Clear();
                        return;
                    }

                    //int index1 = recBuffer.FindIndex(b => b == 0xAA);
                    //int index2 = recBuffer.FindIndex(b => b == 0x55);
                    int index1 = recBuffer.IndexOf(0xAA);
                    int index2 = recBuffer.IndexOf(0x55);
                    if (index1 + 1 == index2)
                    {
                        if (index1 > 0)
                        {
                            recBuffer.RemoveRange(0, index1);
                        }
                       

                        if (recBuffer[0] == 0xAA && recBuffer[1] == 0x55 && recBuffer[2] == 0x64)
                        {
                            byte[] byteLength = recBuffer.GetRange(3, 2).ToArray();
                            int dataLength = BitConverter.ToUInt16(byteLength.Reverse<byte>().ToArray(), 0);
                            if (recBuffer.ToArray().Length >= dataLength)
                            {
                                List<byte> listRec = recBuffer.GetRange(0, dataLength);
                                if (Protocol.CheckCRC(listRec.ToArray()))
                                {
                                    //string strByte = Common.ConvertDataBySpace(listRec.ToArray());
                                    byte[] recData = recBuffer.GetRange(6, dataLength - 8).ToArray();//接收的数据域数据
                                                                                                     // RTU 设备信息
                                    if (listRec[5] == 0x01)
                                    {
                                        isReadDeviceSuccess = true;
                                        if (!GetDeviceInfo(recData))
                                        {
                                            Messages.ShowAlertDialog("读取设备信息失败！", false);
                                        }
                                    }

                                    if (listRec[5] == 0x02)//读设备配置返回信息
                                    {
                                        isSuccess = GetDeviceConfig(recData);
                                        if (isSuccess)
                                        {
                                            this.Invoke((MethodInvoker)delegate
                                            {
                                                paraConfig.SetConfig(rtuConfigInfo);
                                            });
                                        }
                                    }

                                    if (listRec[5] == 0x03)//写设备配置返回信息
                                    {
                                        isSuccess = true;
                                    }

                                    if (listRec[5] == 0x04)//传感器调试返回信息
                                    {
                                        isSuccess = true;
                                        //ShowMessage(System.Text.Encoding.Default.GetString(recData));
                                        if (debugInfo != null)
                                        {
                                            //Messages.ShowAlertDialog("读取设备信息1！" + string.Join(",", recData.ToArray()), true);
                                            //Messages.ShowAlertDialog("读取设备信息！" + System.Text.Encoding.Default.GetString(recData, 2, recData.Length-2 ), true);
                                            debugInfo.ShowMessage(System.Text.Encoding.Default.GetString(recData, 2, recData.Length - 2), recData[0], recData[1]);
                                        }
                                    }

                                    if (listRec[5] == 0x09)//数据调试返回信息
                                    {
                                        isSuccess = true;
                                        if (dataDebugInfo != null)
                                        {
                                            dataDebugInfo.ShowMessage(System.Text.Encoding.Default.GetString(recData, 0, recData.Length));
                                        }
                                    }

                                    if (listRec[5] == 0x05)//设备升级返回
                                    {
                                        if (recData[0] == 0x00)
                                        {
                                            upgradeStatus = 0;
                                        }

                                        if (recData[0] == 0xF1)
                                        {
                                            upgradeStatus = 1;
                                        }

                                        if (recData[0] == 0xF2)
                                        {
                                            upgradeStatus = 2;
                                        }

                                        if (recData[0] == 0xF3)
                                        {
                                            upgradeStatus = 3;
                                        }
                                        //recBuffer.RemoveRange(0, 11);
                                    }

                                    if (listRec[5] == 0x06)//设备时间设置返回信息
                                    {
                                        isSuccess = true;
                                    }

                                    if (listRec[5] == 0x0A)//流量堰槽设置
                                    {
                                        isSuccess = true;
                                        if (recData.Length == 1025)
                                        {
                                            for (int i = 0; i < flowData.Length; i++)
                                            {
                                                flowData[i] = BitConverter.ToInt32(recData, i * 4 + 1);
                                            }
                                        }
                                    }

                                    if (listRec[5] == 0x0B)//写入流量堰槽设置返回信息
                                    {
                                        isSuccess = true;
                                        if (recData[1] == 0x00)
                                        {
                                            Messages.ShowAlertDialog("写入流量堰槽设置成功！", true);
                                        }

                                        if (recData[1] == 0xFF)
                                        {
                                            Messages.ShowAlertDialog("写入流量堰槽设置失败！", false);
                                        }
                                    }

                                    if (listRec[5] == 0x0C)//图片采集返回信息
                                    {
                                        isSuccess = true;
                                        if (cameraPicture != null)
                                        {
                                            if (recData[1] == 0x03)
                                            {
                                                if (isCollectImage)
                                                {
                                                    byte[] data = new byte[2];
                                                    data[0] = recData[3];
                                                    data[1] = recData[2];
                                                    totalPackages = BitConverter.ToUInt16(data, 0);
                                                    SetImageCmd(1);
                                                }
                                            }
                                            else if (recData[1] == 0x05 || recData[1] == 0xF1 || recData[1] == 0xF2)
                                            {

                                            }
                                            else
                                            {
                                                SendCmd(Protocol.GetWriteDeviceCmd(0x0C, new byte[2] { Convert.ToByte(deviceIndex), 0x02 }));
                                                Thread.Sleep(1000);
                                            }

                                            if (cameraPicture != null)
                                            {
                                                cameraPicture.ShowInfo(recData[1]);
                                            }
                                        }
                                    }

                                    if (listRec[5] == 0x0D)//图片上传返回信息
                                    {
                                        imageStatus = recData[1];
                                        if (recData[1] == 0x00)
                                        {
                                            byte[] data = new byte[2];
                                            data[0] = recData[3];
                                            data[1] = recData[2];
                                            int intPackages = BitConverter.ToUInt16(data, 0);
                                            byte[] imageData = new byte[recData.Length - 6];
                                            Array.Copy(recData, 6, imageData, 0, imageData.Length);
                                            if (!imageDataPackages.ContainsKey(intPackages))
                                            {
                                                imageDataPackages.Add(intPackages, imageData);
                                            }
                                            else
                                            {
                                                imageDataPackages[intPackages] = imageData;
                                            }

                                            indexPackages = intPackages;
                                            if (indexPackages == totalPackages)
                                            {
                                                if (cameraPicture != null)
                                                {
                                                    string strPath = System.Windows.Forms.Application.StartupPath + "\\image\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                                                    List<byte> listTemp = new List<byte>();
                                                    foreach (var s in imageDataPackages)
                                                    {
                                                        listTemp.AddRange(s.Value);
                                                    }

                                                    if (Common.CreateImageFile(strPath, listTemp.ToArray()))
                                                    {
                                                        cameraPicture.ShowImage(strPath);
                                                    }
                                                    cameraPicture.ShowInfo(6);//采集完成
                                                                              //Thread.Sleep(1000);
                                                }
                                            }
                                            else
                                            {
                                                SetImageCmd(indexPackages + 1);
                                            }

                                            if (cameraPicture != null)
                                            {
                                                cameraPicture.ShowInfo("采集图片开始上传 " + Convert.ToInt16(Math.Round((double)indexPackages / totalPackages, 2, MidpointRounding.AwayFromZero) * 100).ToString() + "%");
                                            }
                                        }
                                        else
                                        {
                                            if (recData[1] == 0xFF)
                                            {
                                                if (cameraPicture != null)
                                                {
                                                    cameraPicture.ShowInfo(0xFF); //图片缓存不存在
                                                }
                                            }
                                        }
                                    }

                                    if (listRec[5] == 0x0E)//读取累计流量返回信息
                                    {
                                        isSuccess = true;
                                        byte[] data = new byte[recData.Length - 1];
                                        Array.Copy(recData, 1, data, 0, data.Length);
                                        totalFlowValue = Convert.ToDecimal(BitConverter.ToUInt64(data.Reverse<byte>().ToArray(), 0) / 100000.0);
                                    }

                                    if (listRec[5] == 0x0F)//写入累计流量返回信息
                                    {
                                        isSuccess = true;
                                        if (recData[1] == 0x00)
                                        {
                                            Messages.ShowAlertDialog("写入累计流量成功！", true);
                                        }

                                        if (recData[1] == 0xFF)
                                        {
                                            Messages.ShowAlertDialog("写入累计流量失败！", false);
                                        }
                                    }

                                    if (listRec[5] == 0x10)//历史数据返回信息
                                    {
                                        if (recData[0] == 0x01)//历史数据起始时间返回信息
                                        {
                                            hisDataStartTime = Convert.ToDateTime(2000 + Convert.ToUInt16(recData[1]) + "-" + Convert.ToUInt16(recData[2]).ToString().ToString().PadLeft(2, '0') + "-" + Convert.ToUInt16(recData[3]).ToString().ToString().PadLeft(2, '0')
                                                            + " " + Convert.ToUInt16(recData[4]).ToString().ToString().PadLeft(2, '0') + ":" + Convert.ToUInt16(recData[5]).ToString().ToString().PadLeft(2, '0') + ":00");
                                            string strMsg = "历史数据开始时间：" + Convert.ToDateTime(hisDataStartTime).ToString("yyyy-MM-dd HH:mm:ss");
                                            this.Invoke((MethodInvoker)delegate
                                            {
                                                labStartTime.Text = strMsg;
                                                labEndTime.Text = "历史数据结束时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + ":00";
                                                //labZq.Text = "数据上传周期：" + Convert.ToUInt16(rtuConfigInfo.ReportingCycle) + "分钟";
                                                cbbNud1.SelectedIndex = GetItemIndex(cbbNud1, Convert.ToUInt16(rtuConfigInfo.ReportingCycle));//数据加报周期
                                                dateEditStart.EditValue = Convert.ToDateTime(hisDataStartTime).ToString("yyyy-MM-dd");
                                                dateEditEnd.EditValue = DateTime.Now.ToString("yyyy-MM-dd");
                                            });
                                            Messages.ShowAlertDialog(strMsg, true);
                                        }

                                        if (recData[0] == 0x02)//历史数据返回信息
                                        {
                                            InitHisData(recData);
                                            //Messages.SaveLog(string.Format("接受InitHisData:{0}", ConvertDataBySpace(recData)));
                                        }
                                        isSuccess = true;
                                    }

                                    if (listRec[5] == 0x11)//读取水位流量标定
                                    {
                                        isSuccess = true;
                                        byte[] data = new byte[recData.Length - 1];
                                        Array.Copy(recData, 1, data, 0, data.Length);
                                        waterLevelSetting.InitValue(data);
                                    }

                                    if (listRec[5] == 0x12)//写入水位流量标定
                                    {
                                        isSuccess = true;
                                        if (recData[1] == 0x00)
                                        {
                                            Messages.ShowAlertDialog("写入水位流量标定成功！", true);
                                        }

                                        if (recData[1] == 0xFF)
                                        {
                                            Messages.ShowAlertDialog("写入水位流量标定失败！", false);
                                        }
                                    }

                                    if (listRec[5] == 0x13)//清除历史数据返回
                                    {
                                        isSuccess = true;
                                        if (recData[1] == 0x00)
                                        {
                                            Messages.ShowAlertDialog("清除历史数据成功！", true);
                                        }

                                        if (recData[1] == 0xFF)
                                        {
                                            Messages.ShowAlertDialog("清除历史数据失败！", false);
                                        }
                                    }

                                    if (listRec[5] == 0x14)//读取雨量返回信息
                                    {
                                        isSuccess = true;
                                        byte[] data = new byte[recData.Length - 1];
                                        Array.Copy(recData, 1, data, 0, data.Length);
                                        totalRainValue = Convert.ToDecimal(BitConverter.ToUInt32(data.Reverse<byte>().ToArray(), 0) / 10.0);
                                    }

                                    if (listRec[5] == 0x15)//写入雨量返回信息
                                    {
                                        isSuccess = true;
                                        if (recData[0] == 0x00)
                                        {
                                            Messages.ShowAlertDialog("写入雨量成功！", true);
                                        }

                                        if (recData[0] == 0xFF)
                                        {
                                            Messages.ShowAlertDialog("写入雨量失败！", false);
                                        }
                                    }

                                    recBuffer.RemoveRange(0, dataLength);
                                }
                                else
                                {
                                    recBuffer.Clear();
                                    //recBuffer.RemoveRange(0, dataLength);
                                    //Messages.ShowAlertDialog("校验码错误！", false);
                                }
                            }
                            
                        }
                    }
                    else
                    {
                        recBuffer.Clear();
                    }
                }

                //if (recBuffer[0] == 0xAA && recBuffer[1] == 0x55 && recBuffer[2] == 0x64)
                //{
                //    byte[] byteLength = recBuffer.GetRange(3, 2).ToArray();
                //    int dataLength = BitConverter.ToUInt16(byteLength.Reverse<byte>().ToArray(), 0);
                //    List<byte> listRec = recBuffer.GetRange(0, dataLength);
                //    if (Protocol.CheckCRC(listRec.ToArray()))
                //    {
                //        string strByte = Common.ConvertDataBySpace(listRec.ToArray());

                //        byte[] recData = recBuffer.GetRange(6, dataLength - 8).ToArray();//接收的数据域数据
                //                                                                         // RTU 设备信息
                //        if (listRec[5] == 0x01)
                //        {
                //            isSuccess = true;
                //            if (!GetDeviceInfo(recData))
                //            {
                //                Messages.ShowAlertDialog("读取设备信息失败！", false);
                //            }
                //        }

                //        if (listRec[5] == 0x02)//读设备配置返回信息
                //        {
                //            isSuccess = GetDeviceConfig(recData);
                //            if (isSuccess)
                //            {
                //                if (this.IsHandleCreated)
                //                {
                //                    this.Invoke((MethodInvoker)delegate
                //                    {
                //                        paraConfig.SetConfig(rtuConfigInfo);
                //                    });
                //                }
                //            }
                //        }

                //        if (listRec[5] == 0x03)//写设备配置返回信息
                //        {
                //            isSuccess = true;
                //            //Common.ShowMessage("保存设备配置成功！");
                //            //recBuffer.RemoveRange(0, 9);
                //        }


                //        if (listRec[5] == 0x04)//传感器调试返回信息
                //        {
                //            isSuccess = true;
                //            ShowMessage(System.Text.Encoding.Default.GetString(recData));
                //        }

                //        if (listRec[5] == 0x05)//设备升级返回
                //        {
                //            if (recData[0] == 0x00)
                //            {
                //                upgradeStatus = 0;
                //            }

                //            if (recData[0] == 0xF1)
                //            {
                //                upgradeStatus = 1;
                //            }

                //            if (recData[0] == 0xF2)
                //            {
                //                upgradeStatus = 2;
                //            }

                //            if (recData[0] == 0xF3)
                //            {
                //                upgradeStatus = 3;
                //            }
                //            //recBuffer.RemoveRange(0, 11);
                //        }

                //        if (listRec[5] == 0x06)//设备时间设置返回信息
                //        {
                //            isSuccess = true;
                //        }

                //        if (listRec[5] == 0x09)//流量堰槽设置
                //        {
                //            isSuccess = true;
                //            flowData = GetFlowData(recData);
                //        }

                //        if (listRec[5] == 0x10)//写入流量堰槽设置返回信息
                //        {
                //            isSuccess = true;
                //        }
                //    }
                //    else
                //    {
                //        Messages.ShowAlertDialog("校验码错误！", false);
                //    }

                //    //if (recBuffer.Count >= dataLength)
                //    //{
                //    //    recBuffer.RemoveRange(0, dataLength);
                //    //}
                //}
                //recBuffer.Clear();
            }
            catch (Exception ex)
            {
                Messages.SaveLog(ex);
            }
        }

        /// <summary>
        /// 检查发送命令是否成功返回
        /// </summary>
        /// <returns>true,false</returns>
        public bool CheckReturnCmd()
        {
            DateTime dt = DateTime.Now;
            while (true)
            {
                Thread.Sleep(20);
                if (isSuccess)
                {
                    return true;
                }
                TimeSpan ts = DateTime.Now - dt;
                if (ts.TotalSeconds >= 5)
                {
                    return false;
                }
            }
        }


        /// <summary>
        /// 检查发送命令是否成功返回
        /// </summary>
        /// <returns>true,false</returns>
        public bool CheckReturnCmd1()
        {
            for (int m = 0; m < 10; m++)
            {
                if (m == 9)
                {
                    return false;
                }
                Thread.Sleep(200);
                SendDeviceCmd();
                if (isReadDeviceSuccess)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 检查发送命令是否成功返回
        /// </summary>
        /// <returns>true,false</returns>
        public bool CheckReturnCmd2()
        {
            DateTime dt = DateTime.Now;
            while (true)
            {
                Thread.Sleep(20);
                if (isReadDeviceSuccess)
                {
                    return true;
                }
                TimeSpan ts = DateTime.Now - dt;
                if (ts.TotalSeconds >= 5)
                {
                    return false;
                }
            }
        }


        private void Run(Object appName)
        {
            Process ps = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = appName.ToString()
                }
            };
            ps.Start();
        }

        /// <summary>
        /// 设备连接
        /// </summary>
        private void nbClient_ElementClick(object sender, DevExpress.XtraBars.Navigation.NavElementEventArgs e)
        {
            ConnectionForm cf = new ConnectionForm();
            cf.StartPosition = FormStartPosition.CenterScreen;
            cf.ShowDialog();
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        private void nbClose_ElementClick(object sender, DevExpress.XtraBars.Navigation.NavElementEventArgs e)
        {
            try
            {
                Application.ExitThread();
                Thread thtmp = new Thread(new ParameterizedThreadStart(Run));
                object appName = Application.ExecutablePath;
                Thread.Sleep(1);
                thtmp.Start(appName);
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("断开连接失败！" , ex);
            }
        }
        public static string ConvertDataBySpace(Byte[] data)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (Byte b in data)
                {
                    sb.Append(Convert.ToString(b, 16).ToUpper().PadLeft(2, '0'));
                }
                return sb.ToString().Trim();
            }
            catch { return string.Empty; }
        }
        /// <summary>
        /// 串口数据接收
        /// </summary>
        private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //Thread.Sleep(200);
                int count = sp.BytesToRead;
                if (count > 0)
                {
                    DateTime now = DateTime.Now;
                    if (IsLoaded)
                    {
                        statusStrip.Invoke((MethodInvoker)delegate
                        {
                            labInfo2.Text = string.Format("接收数据:{0}字节", count);
                        });
                    }
                    byte[] buffer = new byte[count];
                    sp.Read(buffer, 0, count);
                    recBuffer.AddRange(buffer);
                    //if (count!=32)
                    //{
                    //    Messages.SaveLog(string.Format("接收数据:{0}字节", count));
                    //    Messages.SaveLog(string.Format("接受客户端data:{0}", ConvertDataBySpace(buffer)));
                    //}
                    InitRtuData();

                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("读取协议失败！", ex);
            }
        }

        /// <summary>
        /// 读取设备配置
        /// </summary>
        private void btnReadSetting_Click(object sender, EventArgs e)
        {
            try
            {
                timer2.Enabled = false;
                recBuffer.Clear();
                isSuccess = false;
                SendCmd(Protocol.GetReadDeviceInfoCmd(0x02));
                Thread sub = new Thread(() =>
                {
                    if (CheckReturnCmd())
                    {
                        Messages.ShowAlertDialog("读取设备配置成功！", true);
                    }
                    else
                    {
                        Messages.ShowAlertDialog("读取设备配置失败！", false);
                    }
                });
                sub.IsBackground = true;
                sub.Start();
                timer2.Enabled = true;
            }
            catch(Exception ex)
            {
                Messages.SaveLogDialog("读取设备配置失败！", ex);
            }
        }

        /// <summary>
        /// 保存设备配置
        /// </summary>
        private void btnWriteSetting_Click(object sender, EventArgs e)
        {
            try
            {
                rtuConfigInfo_Before = RTUParameterConfig.ParameterConfig.rtuConfigInfo.Copy();
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("确定要保存设备配置吗?", "保存设备配置", messButton);
                if (dr == DialogResult.OK)
                {
                    if (paraConfig.CheckConfig())
                    {
                        timer2.Enabled = false;
                        recBuffer.Clear();
                        isSuccess = false;
                        byte[] byteWirte = paraConfig.GetConfig();
                        //Messages.ShowAlertDialog("读取设备信息1！" + string.Join(",", listSend.ToArray()), true);
                        //Messages.ShowAlertDialog("读取设备信息1！" + intConfigDataLength, true);
                        List<byte> listData = new List<byte>();
                        listData.AddRange(byteWirte);
                        if (intConfigDataLength == 968)
                        {
                            byteWirte = listData.GetRange(0, 968).ToArray();
                        }
                       SendCmd(Protocol.GetWriteDeviceCmd(0x03, byteWirte));
                        
                        Thread sub = new Thread(() =>
                        {
                            if (CheckReturnCmd())
                            {
                                SendCmd(Protocol.GetReadDeviceInfoCmd(0x07));
                                Thread.Sleep(1000);
                                Messages.ShowAlertDialog("保存设备配置成功！", true);
                            }
                            else
                            {
                                Messages.ShowAlertDialog("保存设备配置失败！", false);
                            }
                        });
                        sub.IsBackground = true;
                        sub.Start();
                        timer2.Enabled = true;
                    }
                }
            }
            catch(Exception ex)
            {
                Messages.SaveLogDialog("保存设备配置失败！" , ex);
            }
        }

        /// <summary>
        /// 显示修改记录
        /// </summary>
        private void btnUpdateLog_Click(object sender, EventArgs e)
        {
            try
            {
                if (paraConfig.CheckConfig())
                {
                    rtuConfigInfo = (RTUParameterConfig.Class.StructData.RtuConfigInfo)Protocol.BytesToStuct(paraConfig.GetConfig(), typeof(RTUParameterConfig.Class.StructData.RtuConfigInfo));
                    UpdateLog ul = new UpdateLog();
                    ul.StartPosition = FormStartPosition.CenterParent;
                    ul.ShowLog(RTUParameterConfig.Class.Protocol.CheckUpdateData(rtuConfigInfo_Before, rtuConfigInfo));
                    ul.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("显示修改记录错误！", ex);
            }
        }

        /// <summary>
        /// 选择页事件
        /// </summary>
        private void xtcMenu_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            //if (xtcMenu.SelectedTabPageIndex == 0)
            //{
            //    timer2.Enabled = true;
            //}
            //else
            //{
            //    timer2.Enabled = false;
            //}
        }

        /// <summary>
        /// 设备信息刷新显示
        /// </summary>
        private void timer2_Tick(object sender, EventArgs e)
        {
            SendDeviceCmd();
            dgvInfo.DataSource = dtDeviceInfo;
        }


        /// <summary>
        /// 实时数据开始读取
        /// </summary>
        private void btnReadReal_Click(object sender, EventArgs e)
        {
            try
            {
                if (!RealDataReadStatus)//开始读取
                {
                    RealDataReadStatus = true;
                    RealDataType = 0;
                    btnReadReal.Text = "结束读取";
                    thSendRealDataCmd.Start();
                    SetRealDataFormStatus(false);
                }
                else//正在读取
                {
                    RealDataReadStatus = false;
                    btnReadReal.Text = "开始读取";
                    thSendRealDataCmd.Abort();
                    SetRealDataFormStatus(true);
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("实时数据读取失败！", ex);
            }
        }

        /// <summary>
        /// 实时数据上报数据
        /// </summary>
        private void btnUpLoadData_Click(object sender, EventArgs e)
        {
            isRealDataUpload = true;
        }

        /// <summary>
        /// 实时数据采集图片
        /// </summary>
        private void btnImageCollect_Click(object sender, EventArgs e)
        {
            isCollectImage = true;
        }

        /// <summary>
        /// 实时数据上报图片
        /// </summary>
        private void btnUploadImage_Click(object sender, EventArgs e)
        {
            isUploadImage = true;
        }

        public class ListItem : Object
        {
            public string Text { get; set; }

            public int Value { get; set; }

            public ListItem(string text, int value)
            {
                this.Text = text;
                this.Value = value;
            }

            public override string ToString()
            {
                return this.Text;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 选择升级文件
        /// </summary>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            try
            {
                //openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "BIN文件|*.bin";
                openFileDialog.RestoreDirectory = true;
                openFileDialog.FileName = "";
                openFileDialog.FilterIndex = 1;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtFile.Text = openFileDialog.FileName;
                    txtCd.Text = Common.FileContent(txtFile.Text).Length.ToString();
                }
            }
            catch(Exception ex)
            {
                Messages.SaveLogDialog("打开升级文件失败！", ex);
            }
        }

        /// <summary>
        /// 升级程序
        /// </summary>
        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                btnUpload.Enabled = false;
                totalPackages = 0;
                indexPackages = 0;
                upgradeStatus = -1;
                if (!isUpgradeStatus)//开始升级
                {
                    if (txtFile.Text == string.Empty)
                    {
                        btnUpload.Enabled = true;
                        Messages.ShowAlertDialog("请选择升级文件！",false);
                        return;
                    }
                    listUpgradeFile.Clear();
                    listUpgradeFile.AddRange(Common.FileContent(txtFile.Text));
                    if (listUpgradeFile.Count == 0)
                    {
                        btnUpload.Enabled = true;
                        Messages.ShowAlertDialog("请检查升级文件是否正确！", false);
                        return;
                    }

                    progressBar.Value = 0;
                    int m = listUpgradeFile.Count % lengthPackages;
                    if (m > 0)      //补包,不足一包1024 字节其余填充0
                    {
                        byte[] temp = new byte[lengthPackages - m];
                        listUpgradeFile.AddRange(temp);
                    }
                    SetUpdateFormStatus(false);
                    Thread.Sleep(2000);
                    totalPackages = listUpgradeFile.Count / lengthPackages;
                    isUpgradeStatus = true;
                    RealDataType = 4;
                    btnUpload.Text = "停止升级";
                    //SetUpdateFormStatus(false);
                }
                else//结束升级
                {
                    RealDataType = 0;
                    isUpgradeStatus = false;
                    progressBar.Value = 0;
                    labProgress.Text = "";
                    btnUpload.Text = "开始升级";
                    SetUpdateFormStatus(true);
                }
                btnUpload.Enabled = true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("打开升级文件失败！", ex);
            }
        }

        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case debugMsg:
                    //接收字符串消息
                    //string msgToStr = Marshal.PtrToStringAnsi(m.LParam); 
                    debugInfo = new DebugInfo(this, m.WParam.ToInt32(), m.LParam.ToInt32());
                    if (m.WParam.ToInt32() == 10)
                    {
                        debugInfo.Text = "流量调试";
                    }
                    debugInfo.StartPosition = FormStartPosition.CenterParent;
                    debugInfo.ShowDialog();
                    break;
                case debugMsg + 1:
                    cameraPicture = new CameraPicture(this, m.WParam.ToInt32(), m.LParam.ToInt32());
                    cameraPicture.StartPosition = FormStartPosition.CenterParent;
                    cameraPicture.ShowDialog();
                    break;
                case debugMsg + 2:
                    flowWeirGroove = new FlowWeirGroove(this, m.WParam.ToInt32(), m.LParam.ToInt32());
                    flowWeirGroove.StartPosition = FormStartPosition.CenterParent;
                    flowWeirGroove.ShowDialog();
                    break;
                case debugMsg + 3:
                    waterLevelSetting = new WaterLevelSetting(this);
                    waterLevelSetting.StartPosition = FormStartPosition.CenterParent;
                    waterLevelSetting.ShowDialog();
                    break;
                default:
                    base.DefWndProc(ref m); //一定要调用基类函数，以便系统处理其它消息。
                    break;
            }
        }

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

        /// <summary>
        /// 重启RTU
        /// </summary>
        private void btnReset_Click(object sender, EventArgs e)
        {
            btnReset.Enabled = false;
            SendCmd(Protocol.GetReadDeviceInfoCmd(0x07));
            Thread.Sleep(2000);
            btnReset.Enabled = true;
        }

        /// <summary>
        /// 加载设备配置
        /// </summary>
        private void btnLoadSetting_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog.DefaultExt = "*.dx";
                openFileDialog.Filter = "设备配置文件|*.dx";
                openFileDialog.FileName = "";
                openFileDialog.RestoreDirectory = true;
                openFileDialog.FilterIndex = 1;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (Path.GetExtension(openFileDialog.FileName).ToLower() == ".dx")
                    {
                        byte[] byteTemp = Common.FileContent(openFileDialog.FileName);
                        if (byteTemp.Length != Protocol.StructToBytes(rtuConfigInfo).Length)
                        {
                            Messages.ShowAlertDialog("加载设备配置文件内容错误！", false);
                            return;
                        }

                        if (GetDeviceConfig(byteTemp))
                        {
                            paraConfig.SetConfig(rtuConfigInfo);
                            Messages.ShowAlertDialog("加载设备配置成功！", true);
                        }
                        else
                        {
                            Messages.ShowAlertDialog("加载设备配置错误！", false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("加载设备配置失败！", ex);
            }
        }

        /// <summary>
        ///导出设备配置
        /// </summary>
        private void btnSaveSetting_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "设备配置文件|*.dx";
                sfd.RestoreDirectory = true;
                sfd.AddExtension = false;
                sfd.FileName = "设备配置";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
                    byte[] data = Protocol.StructToBytes(RTUParameterConfig.ParameterConfig.rtuConfigInfo); 
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Close();
                    Messages.ShowAlertDialog("导出设备配置成功！", true);
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("导出设备配置失败！", ex);
            }
        }

        /// <summary>
        /// 设备信息绑定事件
        /// </summary>
        private void dgvInfo_DataSourceChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in this.dgvInfo.Rows)
            {
                if (dr.Index == 10)
                {
                    DataGridViewButtonCell btnCell = new DataGridViewButtonCell();
                    btnCell.Value = "设置设备时间";
                    dr.Cells[2] = btnCell;
                }

                if (dr.Index == 11)
                {
                    DataGridViewButtonCell btnCell = new DataGridViewButtonCell();
                    btnCell.Value = "上报数据";
                    btnCell.Tag = 1;
                    dr.Cells[2] = btnCell;
                }

                //if (dr.Index == 12)
                //{
                //    DataGridViewButtonCell btnCell = new DataGridViewButtonCell();
                //    btnCell.Value = "上报数据";
                //    btnCell.Tag = 2;
                //    dr.Cells[2] = btnCell;
                //}

                //if (dr.Index == 13)
                //{
                //    DataGridViewButtonCell btnCell = new DataGridViewButtonCell();
                //    btnCell.Value = "上报数据";
                //    btnCell.Tag = 3;
                //    dr.Cells[2] = btnCell;
                //}
            }
        }

        /// <summary>
        /// 设备信息按钮事件
        /// </summary>
        private void dgvInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {           
                if (e.ColumnIndex == 2)
                {
                    if (e.RowIndex == 10)
                    {
                        SetDeviceTime st = new SetDeviceTime(this);
                        st.StartPosition = FormStartPosition.CenterParent;
                        st.ShowDialog();
                    }

                    if (e.RowIndex == 11)
                    {
                        timer2.Enabled = false;
                        recBuffer.Clear();
                        SendCmd(Protocol.GetWriteDeviceCmd(0x08, new byte[1] { 0x01 }));
                        timer2.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                if (e.RowIndex == 10)
                {
                    Messages.SaveLogDialog("打开设备时间设置界面失败！", ex);
                }

                if (e.RowIndex == 11)
                {
                    Messages.SaveLogDialog("上报数据失败！", ex);
                }
            }
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers.CompareTo(Keys.Control) == 0)
            {
                if (e.KeyCode == Keys.W)
                {
                    PassWord pw = new PassWord(this);
                    pw.StartPosition = FormStartPosition.CenterParent;
                    pw.ShowDialog();
                }

                if (e.KeyCode == Keys.H)
                {
                    PassWord1 pw = new PassWord1(this);
                    pw.StartPosition = FormStartPosition.CenterParent;
                    pw.ShowDialog();
                }
            }
        }

        /// <summary>
        /// 数据调试
        /// </summary>
        private void btnDebug_Click(object sender, EventArgs e)
        {
            try
            {
                dataDebugInfo = new AllDebugInfo(this);
                dataDebugInfo.StartPosition = FormStartPosition.CenterParent;
                dataDebugInfo.ShowDialog();
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("打开数据调试失败！", ex);
            }
        }

        /// <summary>
        /// 雨量设置
        /// </summary>
        private void btnRainSet_Click(object sender, EventArgs e)
        {
            try
            {
                TotalRainSetting ts = new TotalRainSetting(this);
                ts.StartPosition = FormStartPosition.CenterParent;
                ts.ShowDialog();
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("打开雨量设置失败！", ex);
            }
        }

        /// <summary>
        /// 累计流量设置
        /// </summary>
        private void BtnFlowSet_Click(object sender, EventArgs e)
        {
            try
            {
                TotalFlowSetting ts = new TotalFlowSetting(this);
                ts.StartPosition = FormStartPosition.CenterParent;
                ts.ShowDialog();
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("打开累计流量设置失败！", ex);
            }
        }

        /// <summary>
        /// 查询历史数据
        /// </summary>
        private void btnSelectTime_Click(object sender, EventArgs e)
        {
            try
            {
                isSuccess = false;
                timer2.Enabled = false;
                recBuffer.Clear();
                SendCmd(Protocol.GetWriteDeviceCmd(0x10, new byte[8] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }));
                Thread sub = new Thread(() =>
                {
                    if (!CheckReturnCmd())
                    {
                        Messages.ShowAlertDialog("查询历史数据失败！", false);
                    }
                });
                sub.IsBackground = true;
                sub.Start();
                timer2.Enabled = true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("查询历史数据失败！", ex);
            }
        }

        /// <summary>
        /// 导出历史数据
        /// </summary>
        private void btnImportData_Click(object sender, EventArgs e)
        {
            try
            {
                if (hisDataStartTime == null)
                {
                    Messages.ShowAlertDialog("请先查询历史数据！", false);
                    return;
                }

                if (dateEditStart.EditValue == null)
                {
                    Messages.ShowAlertDialog("请输入开始时间！", false);
                    return;
                }

                if (dateEditEnd.EditValue == null)
                {
                    Messages.ShowAlertDialog("请输入结束时间！", false);
                    return;
                }

                if (DateTime.Compare(Convert.ToDateTime(dateEditStart.EditValue), Convert.ToDateTime(hisDataStartTime)) < 0)
                {
                    Messages.ShowAlertDialog("开始时间不能小于历史数据开始时间！", false);
                    return;
                }

                if (DateTime.Compare(Convert.ToDateTime(dateEditStart.EditValue), DateTime.Now) > 0)
                {
                    Messages.ShowAlertDialog("开始时间不能大于当前时间！", false);
                    return;
                }

                if (DateTime.Compare(Convert.ToDateTime(dateEditEnd.EditValue), DateTime.Now) > 0)
                {
                    Messages.ShowAlertDialog("结束时间不能大于当前时间！", false);
                    return;
                }

                if (DateTime.Compare(Convert.ToDateTime(dateEditStart.EditValue), Convert.ToDateTime(dateEditEnd.EditValue)) > 0)
                {
                    Messages.ShowAlertDialog("开始时间不能大于结束时间！", false);
                    return;
                }

                int intReportingCycle = (cbbNud1.SelectedItem as ListItem).Value; //Convert.ToUInt16(rtuConfigInfo.ReportingCycle);//数据加报周期
                DateTime dtEnd;
                if (DateTime.Compare(Convert.ToDateTime(dateEditEnd.EditValue), Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"))) >= 0)
                {
                    dtEnd = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + ":00");//.AddMinutes(-1);
                }
                else
                {
                    dtEnd = Convert.ToDateTime(Convert.ToDateTime(dateEditEnd.EditValue).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00").AddMinutes(0 - intReportingCycle);
                }
                dtHisData.Rows.Clear();
                TimeSpan ts = new TimeSpan(dtEnd.Ticks - Convert.ToDateTime(dateEditStart.EditValue).Ticks);
                int dataCount = Convert.ToInt32(ts.TotalMinutes) / intReportingCycle;//历史数据总数
                dtEnd = Convert.ToDateTime(dateEditStart.EditValue).AddMinutes(dataCount * intReportingCycle);//结束时间
                HisDataDownLoad hd = new HisDataDownLoad(this, Convert.ToDateTime(dateEditStart.EditValue), dtEnd, intReportingCycle, dataCount+1);
                hd.StartPosition = FormStartPosition.CenterParent;
                hd.ShowDialog();
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("导出历史数据失败！", ex);
            }
        }

        private void dgvHisData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgvHisData.RowHeadersWidth, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgvHisData.RowHeadersDefaultCellStyle.Font, rectangle, dgvHisData.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter);
        }

        /// <summary>
        /// 清除历史数据
        /// </summary>
        private void btnClearHisData_Click(object sender, EventArgs e)
        {
            try
            {
                //MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                //DialogResult dr = MessageBox.Show("确定要清除历史数据吗?", "清除历史数据", messButton);
                RemoveHistory removeForm = new RemoveHistory(this);
                removeForm.StartPosition = FormStartPosition.CenterScreen;
                removeForm.ShowDialog();
                if (isRemoveHistory)
                {
                    isSuccess = false;
                    timer2.Enabled = false;
                    recBuffer.Clear();
                    //removeDate  2024-08-01 14:03:44
                    string newDate = Regex.Replace(removeDate,"[^0-9]","");
                    newDate = newDate.Substring(2, newDate.Length-2);
                    List<byte> listdate = new List<byte>();
                    listdate.Add(Convert.ToByte(newDate.Substring(0, 2)));
                    listdate.Add(Convert.ToByte(newDate.Substring(2, 2)));
                    listdate.Add(Convert.ToByte(newDate.Substring(4, 2)));
                    listdate.Add(Convert.ToByte(newDate.Substring(6, 2)));
                    listdate.Add(Convert.ToByte(newDate.Substring(8, 2)));
                    listdate.Add(Convert.ToByte(newDate.Substring(10, 2)));

                    SendCmd(Protocol.RemoveHistoryInfoCmd(0x13, listdate));
                    Thread sub = new Thread(() =>
                    {
                        if (!CheckReturnCmd())
                        {
                            Messages.ShowAlertDialog("清除历史数据失败！", false);
                        }
                    });
                    sub.IsBackground = true;
                    sub.Start();
                    timer2.Enabled = true;
                    listdate.Clear();
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("清除历史数据失败！", ex);
            }
        }

        /// <summary>
        /// 加载上一次配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadUpSetting_Click(object sender, EventArgs e)
        {
            try
            {
                paraConfig.SetConfig(rtuConfigInfo_Before);
                Messages.ShowAlertDialog("加载上一次设备配置成功！", true);
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("加载上一次设备配置失败！", ex);
            }
        }
    }
}
